package com.ruoyi.zhgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.TreeBuildUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.sdhsg.pierce.v1.message.api.MessageClient;
import com.sdhsg.pierce.v1.message.api.request.SendMessageRequest;
import com.sdhsg.pierce.v1.message.api.response.SendMessageResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.zhgd.domain.bo.ZjNWarningUsingBo;
import com.ruoyi.zhgd.domain.vo.ZjNWarningUsingVo;
import com.ruoyi.zhgd.domain.ZjNWarningUsing;
import com.ruoyi.zhgd.mapper.ZjNWarningUsingMapper;
import com.ruoyi.zhgd.service.IZjNWarningUsingService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 报警通知短信发送是否启用信息Service业务层处理
 *
 * @author tll
 * @date 2023-11-16
 */
@RequiredArgsConstructor
@Service
@DS("sjcj")
public class ZjNWarningUsingServiceImpl implements IZjNWarningUsingService {

    private final ZjNWarningUsingMapper baseMapper;

    private final ISysDeptService iSysDeptService;

    private final SysDeptMapper sysDeptMapper;

    // 测试用appId
    @Value("${mms.appId}")
    private String appId;
    // 测试用密钥
    @Value("${mms.secret}")
    private String secret;
    // 测试环境
    @Value("${mms.active}")
    private String active;
    // 测试环境发送人
    @Value("${mms.msgCreator}")
    private String msgCreator;

    /**
     * 查询报警通知短信发送是否启用信息列表
     */
    @Override
    public ZjNWarningUsing queryPageList() {
        ZjNWarningUsingBo bo = new ZjNWarningUsingBo();
        LambdaQueryWrapper<ZjNWarningUsing> lqw = buildQueryWrapper(bo);
        return baseMapper.selectOne(lqw);
    }

    /**
     * 查询报警通知短信发送是否启用信息
     */
    @Override
    public ZjNWarningUsingVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询报警通知短信发送是否启用信息列表
     */
    @Override
    public List<ZjNWarningUsingVo> queryList(ZjNWarningUsingBo bo) {
        LambdaQueryWrapper<ZjNWarningUsing> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZjNWarningUsing> buildQueryWrapper(ZjNWarningUsingBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZjNWarningUsing> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUsingFlag() != null, ZjNWarningUsing::getUsingFlag, bo.getUsingFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getBusiness()), ZjNWarningUsing::getBusiness, bo.getBusiness());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getUsingMsgHnt()), ZjNWarningUsing::getUsingMsgHnt, bo.getUsingMsgHnt());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getUsingMsgSy()), ZjNWarningUsing::getUsingMsgSy, bo.getUsingMsgSy());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getUsingMsgZlyj()), ZjNWarningUsing::getUsingMsgZlyj, bo.getUsingMsgZlyj());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getUsingAppHnt()), ZjNWarningUsing::getUsingAppHnt, bo.getUsingAppHnt());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getUsingAppSy()), ZjNWarningUsing::getUsingAppSy, bo.getUsingAppSy());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getUsingAppZlyj()), ZjNWarningUsing::getUsingAppZlyj, bo.getUsingAppZlyj());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getDeptId()), ZjNWarningUsing::getDeptId, bo.getDeptId());
        lqw.eq(ZjNWarningUsing::getDelFlag, "0");
        return lqw;
    }

    /**
     * 新增报警通知短信发送是否启用信息
     */
    @Override
    public Boolean insertByBo(ZjNWarningUsingBo bo) {
        ZjNWarningUsing add = BeanUtil.toBean(bo, ZjNWarningUsing.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改报警通知短信发送是否启用信息
     */
    @Override
    public Boolean updateByBo(ZjNWarningUsingBo bo) {
        ZjNWarningUsing update = BeanUtil.toBean(bo, ZjNWarningUsing.class);
        validEntityBeforeSave(update);
//        if (ObjectUtils.isEmpty(bo.getUsingFlag())) {
//            throw new ServiceException("参数不能为空");
//        }
//        ZjNWarningUsing data = baseMapper.selectList().get(0);
        update.setDelFlag("0");
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZjNWarningUsing entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除报警通知短信发送是否启用信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 发送短信通知
     * @param receiveAddr 收件人手机号数组
     * @param content 短信内容
     *       推送失败 返1 成功 返0
     */
    @Override
    public int send(List<String> receiveAddr, String content) {
        // 过滤手机号数组的空值
        receiveAddr = receiveAddr.stream().filter(e -> e!=null && ! e.isEmpty()).collect(Collectors.toList());
        // 是否用户管理平台统一用户，接口参数中校验用户唯一标识是否是用户管理平台的标识，如已同步用户管理平台数据传true，否则传输false
        boolean isUnifiedUser = true;
        MessageClient client = new MessageClient();
        SendMessageRequest request = new SendMessageRequest();
        request.setAppId(appId);
        request.setType(SendMessageRequest.MessageType.SMS);
//        request.setTitle("SDK发送短信测试");
        SendMessageRequest.Receivers receivers = new SendMessageRequest.Receivers();
        receivers.setReceiveAddr(receiveAddr);
        request.setReceivers(receivers);
        request.setContent(content);
        request.setMsgCreator(msgCreator);

        SendMessageResponse response = null;
        try {
            response = client.sendMessage(secret, request, isUnifiedUser, active);
            // 推送失败 返1 成功 返0
            if (!response.getSuccess()) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        return 0;
    }

    @Override
    public TableDataInfo<ZjNWarningUsingVo> page(PageQuery pageQuery, ZjNWarningUsingBo bo) {
        Page<ZjNWarningUsingVo> data = baseMapper.page(pageQuery.build(), bo);
        return TableDataInfo.build(data);
    }

    /**
     * (该数据是指二级单位)
     * 如果是二级单位的上级 当前用户数据dept_level>2,即dept_level=0 or dept_level=1
     * 如果是二级单位的同级 当前用户数据 dept_level为null 且 当前用户数据parent_id == 二级单位parent_id
     * 如果是二级单位的同级 当前用户数据parent_id == 二级单位parent_id
     * 如果是二级单位 dept_level = '2'
     * 如果是二级单位的下级 当前用户数据ancestors 包含 二级单位dept_id
     * @param deptId
     */
    @Override
    public List<SysDept> getDeptTreeTop(Long deptId) {
        List<SysDept> res = new ArrayList<>();
        // 获取当前用户部门信息
        SysDept sysDept = sysDeptMapper.getById(deptId);

        // 获取二级单位
        List<SysDept> secList = sysDeptMapper.getSecList();
        List<Long> parents = secList.stream().map(SysDept::getParentId).collect(Collectors.toList());

        // 判断是否二级单位
        SysDept data = sysDeptMapper.isSecUnit(deptId);
        if (ObjectUtils.isEmpty(data)) { // 不是二级单位,判断是上级,同级,下级
            // 是否上级
            if (ObjectUtils.isNotEmpty(sysDept.getDeptLevel()) && ("0".equals(sysDept.getDeptLevel()) || "1".equals(sysDept.getDeptLevel()))) {
                // 查看全部,返回全部
                res = secList;
            }
            // 是否同级是公司领导
            for (Long parent : parents) {
                if ( ObjectUtils.isEmpty(sysDept.getDeptLevel()) && ObjectUtils.isNotEmpty(sysDept.getParentId()) && parent.equals(sysDept.getParentId())) {
                    // 查看全部
                    res = secList;
                }
            }
            // 是否同级非公司领导
            for (Long parent : parents) {
                if (ObjectUtils.isNotEmpty(sysDept.getParentId()) && parent.equals(sysDept.getParentId())) {
                    // 无法查看
                    break;
                }
            }
            // 是否下级
            if (ObjectUtils.isNotEmpty(sysDept.getAncestors())) {
                String ancestors = sysDept.getAncestors();
                for (SysDept dept : secList) {
                    if (ancestors.contains(dept.getDeptId().toString())) {
                        // 返回当前二级单位
                        res.add(dept);
                    }
                }

            }
        } else { // 是二级单位,返回当前用户部门信息
            res.add(sysDept);
        }
        return res;
    }



    /**
     * 获取部门树列表 业务页面左侧结构树 第一层
     * @param dept
     * @return
     */
    @Override
    public List<Tree<Long>> businessDeptTreeTop(SysDept dept) {
        Long deptId = LoginHelper.getDeptId();
        List<SysDept> collect = getDeptTreeTop(deptId);
        List<Tree<Long>> list = TreeBuildUtils.build(collect, (de, tree) ->
            tree.setId(de.getDeptId())
                .setParentId(de.getParentId())
                .setName(de.getDeptName())
                .setWeight(de.getOrderNum()));
//        if (CollectionUtils.isNotEmpty(collect)) {
//            // 校验预警通知表zj_n_warning_using是否存在对应数据,如果不存在则新增
//            QueryWrapper<ZjNWarningUsing> wrapper = new QueryWrapper<>();
//            wrapper.eq("del_flag", "0");
//            List<ZjNWarningUsing> warningUsings = baseMapper.selectList(wrapper);
//            // 判断二级单位数与该表数据是否一致
//            if (collect.size() != warningUsings.size()) {
//                // 不一致,删除zj_n_warning_using表数据后添加
//                baseMapper.deleteBatchIds(warningUsings);
//                for (SysDept sysDept : collect) {
//                    ZjNWarningUsing entity = new ZjNWarningUsing();
//                    entity.setDelFlag("0");
//                    entity.setDeptId(sysDept.getDeptId().toString());
//                    entity.setUsingMsgHnt(Long.valueOf(0));
//                    entity.setUsingMsgSy(Long.valueOf(0));
//                    entity.setUsingMsgZlyj(Long.valueOf(0));
//                    entity.setUsingAppHnt(Long.valueOf(0));
//                    entity.setUsingAppSy(Long.valueOf(0));
//                    entity.setUsingAppZlyj(Long.valueOf(0));
//                    baseMapper.insert(entity);
//                }
//            }
//        }
        return list;
    }

    @Override
    public List<ZjNWarningUsingVo> selectByWgroupId(Integer id) {
        return baseMapper.selectByWgroupId(id);
    }


    @Override
    public List<ZjNWarningUsingVo> selectByygroupId(Integer id) {
        return baseMapper.selectByygroupId(id);
    }
}
